package edu.dali.enterprise_test.service.auth.impl;

import edu.dali.enterprise_test.dao.mapper.auth.AuthenticationMapper;
import edu.dali.enterprise_test.dao.mapper.auth.PermissionMapper;
import edu.dali.enterprise_test.dao.mapper.auth.RoleMapper;
import edu.dali.enterprise_test.model.Pager;
import edu.dali.enterprise_test.model.vo.Dto;
import edu.dali.enterprise_test.model.vo.SysPermission;
import edu.dali.enterprise_test.model.vo.SysRole;
import edu.dali.enterprise_test.service.auth.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    private AuthenticationMapper authenticationMapper;

    @Override
    public Pager<SysRole> getRoles(Dto dto) {
        Pager p = new Pager();

        List<SysRole> roles = roleMapper.getRoles(dto);
        int count = roleMapper.getRolesCount(dto);
        p.setCode(0);
        p.setData(roles);
        p.setCount(count);
        return p;
    }

    @Override
    public void insertRole(SysRole role) {
        authenticationMapper.insertRole(role);
        for (SysPermission permission : role.getPermissions()) {
            Dto dto = new Dto();
            dto.put("role_id" , role.getId());
            dto.put("permission_id" , permission.getId());
            authenticationMapper.insertRolePermission(dto);
        }
    }

    @Override
    public SysRole selectRole(Dto dto) {
        SysRole role = roleMapper.selectRole(dto);
        Dto rdto = new Dto();
        rdto.put("roleid" , role.getId());
        List<SysPermission> perms = roleMapper.getRolePerms(rdto);
        role.setPermissions(perms);
        return role;
    }

    @Override
    public void updateRole(SysRole role) {
        authenticationMapper.updateRoleUser(role);
        Dto dto = new Dto();
        dto.put("role_id" , role.getId());
        authenticationMapper.deleteRolePermission(dto);
        for (SysPermission perm : role.getPermissions()) {
            Dto pDto = new Dto();
            pDto.put("role_id" , role.getId());
            pDto.put("permission_id" , perm.getId());
            authenticationMapper.insertRolePermission(pDto);
        }

    }

    @Override
    public void deleteRole(SysRole role) {
        Dto dto = new Dto();
        dto.put("role_id" , role.getId());
        authenticationMapper.deleteRolePermission(dto);
        roleMapper.deleteRole(role);
    }
}
